﻿package classes.fire  
{
	import flash.display.*;
	import flash.events.*;
	import flash.system.Security;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.utils.Timer;
	import flash.text.*;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import fl.controls.Button;
	import fl.transitions.*;
	import fl.transitions.easing.*;
	import flash.geom.Point;
	import flash.display.BitmapData;
	
	import com.mttang.common.InterfaceCommon;
	import classes.GameSetting;
	import classes.utils.KeySets;
	import classes.utils.PopKeys;
	import com.mttang.event.CommonEvent; 
	import classes.audio.AudioRockman;
	import classes.audio.Audio;
	import classes.fire.ManPetLayer;
	import classes.bonus.BonusRockman;
	import com.mttang.utils.PopupWindow;

	public class PopStone extends MovieClip implements InterfaceCommon {

		private static const W:uint = 500; 										//场地宽
		private static const H:uint = 480; 										//场地高
		private static const MAP_UNIT:uint = 30; 								//地图元素尺寸
		private static const L:uint = 15;										//
		private static const ROW:uint = 3; 										//初始球的row
		private static const TOTALROW:uint = 15; 								//总的row
		private static const TOTALCOL:uint = 13; 								//总的col
		private static const RADIUS:uint = 30; 									//球半径
		//stone发射有关的参数
		private static const MINI:uint = 3; 									//设置最小几次未得分增加stone
		private var _vx:Number;													//
		private var _vy:Number;													//
		private var _V:Number;													//
		private var _angle:Number;												//发射时候的角度；
		private var initX:Number;												//
		private var initY:Number;												//
		private var initMouseX:Number;											//
		private var initMouseY:Number;											//
		private var _gameLayer:MovieClip;										//游戏层
		private var _shooter:Shooter;											//发射器
		private var _tween:Tween;												//
		//人物和宠物相关参数
		private var _saveData:Object;											//共享对象存储
		private var manPetLayer:ManPetLayer;									//人和宠物的显示层
		private var _playTimer:Timer;											//背景音乐轮播时间
		private var _bonus:Bonus;												//奖励方法类
		private var _totalRockNum:Number = 0;									//本关的岩石数
		private var _totalMoney:Number = 0;										//本关得到的金钱
		private var _levelUp:LevelUp;											//升级对话框
		private var _exitGame:ExitGame;											//退出游戏对话框
		
		private var bubbleArray:Array = new Array(); 							//用来存储所有stone的引用的二维数组，最常用的
		private var dropArr:Array = new Array(); 								//放置待消除的数组
		private var temDropArr:Array = new Array(); 							//临时放置待消除的数组
		private var bullet:Bubble; 												//发射的岩石
		private var nextBullet:Bubble; 											//下一个发射的岩石
		private var currentBullet:Bubble; 										//当前待发射的岩石
		private var wall:StoneWall;												//周围墙壁
		private var row:uint; 													//bubbleArray的row
		private var col:uint; 													//bubbleArray 的 col
		private var core_r:uint; 												//搜索网络的起始球的row
		private var core_c:uint; 												//搜索网络的起始球的col
		private var keysets:KeySets;											//键盘设置	
		private var lenArra:Array = new Array(); 								//衡量搜索相同颜色stone完毕的尺子，即递归出口
		private var dropLenArr:Array = new Array(); 							//衡量搜索相连接stone完毕的尺子
		private var sameBubbleTotal:Array; 										//搜索到相同stone最终放置的数组，如果大于二，drop
		private var _sameBubbleTotal:Array = [];								//暂时存储相同颜色的岩石
		private var _xkFlag:Boolean = false;									//悬空标记
		private var totalScore:uint = 0; 										//总得分
		private var checkNum:uint = 0; 											//检查几次没得分
		private var finalScore:uint; 											//gameover时显示的总分

		public function PopStone() {
			
		}
		
		public function rock_pause():void //所有场景可以暂停/播放；
		{
			removeEventListener(Event.ENTER_FRAME, enFrameHandler);
			stage.removeEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			removeEventListener(Event.ENTER_FRAME, onFrameHandler);
			removeEventListener(Event.ENTER_FRAME, startEff);
			if (_playTimer) {
				_playTimer.removeEventListener(TimerEvent.TIMER, playTimerHandler);
				_playTimer.stop();
			}
		}

		public function rock_play():void //
		{
			addEventListener(Event.ENTER_FRAME, enFrameHandler);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			addEventListener(Event.ENTER_FRAME, onFrameHandler);
			addEventListener(Event.ENTER_FRAME, startEff);
			if (_playTimer) {
				_playTimer.addEventListener(TimerEvent.TIMER, playTimerHandler);
				_playTimer.start();
			}
		}

		public function rock_close():void //关闭清除当前的场景;swf文件的声音，flv在这里清除;
		{
			clearUp();
			if (_gameLayer) {
				removeChild(_gameLayer);
				_gameLayer = null;
			}			
			stopBgMusic();
		}

		public function cfgSound(status:String):void //控制声音;	
		{

		}

		public function setData(_data:Object):void //所有的场景通过这个接口获取数据对象;
		{
			Security.allowDomain("*");
			trace("in game plane");
			gamePort();
		}
		
		private function gamePort():void {
			_saveData=SharedObject.getLocal(GameSetting.saveSoData).data.dataRockman[GameSetting.index-1];
			initGame();			
			//播放背景音乐
			playBgMusic();			
			//布局人物宠物
			layoutManPet();			
			//布局分数显示面板
			_bonus = new Bonus();
			addChildAt(_bonus, numChildren);
			_bonus.init();
			_bonus.y = GameSetting.OFFSETY;
		}
		
		//键盘设置属性
		public function set keySets(value:KeySets):void{
			keysets = value;
			addEventListener(Event.ENTER_FRAME, enFrameHandler, false, 0, true);
		}
		
		private function enFrameHandler(e:Event):void {
			//处理键盘事件
			if (PopKeys.isDown(49)) {
				exitGame();
				//dispatchEvent(new Event(CommonEvent.BACK_EVENT));				
			}
			
			if (PopKeys.isDown(27)) {	
				exitGame();
				//dispatchEvent(new Event(CommonEvent.BACK_EVENT));		
			}
		}
		
		private function exitGame():void {
			rock_pause();
			_exitGame = new ExitGame();
			PopupWindow.init(stage);
			PopupWindow.show(_exitGame);
			_exitGame.btn_yes.addEventListener(MouseEvent.CLICK, exitYesHandler);
			_exitGame.btn_no.addEventListener(MouseEvent.CLICK,exitNoHandler);
		}
	
		private function exitYesHandler(e:MouseEvent):void {
			closeExitGame();
			dispatchEvent(new Event(CommonEvent.BACK_EVENT));
		}
		
		private function exitNoHandler(e:MouseEvent):void {
			closeExitGame();
			rock_play();
			//gamePort();			
		}
		
		private function closeExitGame():void {
			_exitGame.btn_yes.removeEventListener(MouseEvent.CLICK, exitYesHandler);
			_exitGame.btn_no.removeEventListener(MouseEvent.CLICK,exitNoHandler);
			PopupWindow.close();
			_exitGame = null;
		}
		
		private function layoutManPet():void {
			//trace(_saveData.user.manid);
			manPetLayer = new ManPetLayer();
			addChildAt(manPetLayer, numChildren);
			manPetLayer.setData(_saveData);
		}

		private function initGame():void {
			stage.scaleMode = StageScaleMode.NO_SCALE;
			//stage.align = StageAlign.TOP_LEFT;
			//布置初始场景
			layoutGame();			
		}

		private function layoutGame():void {
			//游戏容器初始化
			_gameLayer = new MovieClip();
			_gameLayer.rotation = 180;
			_gameLayer.x = W+GameSetting.OFFSETX;
			_gameLayer.y = H;
			_gameLayer.mouseChildren = false;
			//布置游戏3边的墙
			wall = new StoneWall();
			_gameLayer.addChildAt(wall, _gameLayer.numChildren);
			//设置发射器
			layoutShooter();
			//设置初始化岩石
			layoutInitStone();	
			addChildAt(_gameLayer, numChildren);			
			//晃动游戏背景容器
			shakeLayer();
		}
		//设置发射器
		private function layoutShooter():void {
			//发射器待添加UI show 一个发射的装置
			_shooter = new Shooter();
			_shooter.x = GameSetting.stageWidth/2- _shooter.width+GameSetting.OFFSETX;
			_shooter.y = GameSetting.OFFSETY;
			addChild(_shooter);
			_shooter.initShooter();
			stage.addEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			//创建待发射的stone
			currentBullet = new Bubble();
			currentBullet.createBubble();
			currentBullet.x = _shooter.x-currentBullet.width/2;
			currentBullet.y = _shooter.y - currentBullet.height / 2 - 2;
			addChild(currentBullet);			
			//发射准备
			setBullet();
		}
		//设置初始化岩石
		private function layoutInitStone():void {			
			//布置stone
			for (var r:uint = 0; r < TOTALROW; r++){
				bubbleArray[r] = new Array();
				if (r < ROW){
					for (var c:uint = 0; c < TOTALCOL + 2; c++){
						if (r % 2 == 0){
							if (c > TOTALCOL-1){
								bubbleArray[r][c] == null;
							} else {
								bubbleArray[r][c] = new Bubble();
								bubbleArray[r][c].createBubble(true);	
								_gameLayer.addChildAt(bubbleArray[r][c], _gameLayer.numChildren);
								bubbleArray[r][c].x = c * MAP_UNIT + MAP_UNIT;
								bubbleArray[r][c].y = r * MAP_UNIT - MAP_UNIT;
							}
						} else {
							if (c >= TOTALCOL-1){
								bubbleArray[r][c] == null;
							} else {
								bubbleArray[r][c] = new Bubble();
								bubbleArray[r][c].createBubble(true);	
								_gameLayer.addChildAt(bubbleArray[r][c], _gameLayer.numChildren);
								bubbleArray[r][c].x = c * MAP_UNIT + 3 * MAP_UNIT / 2;
								bubbleArray[r][c].y = r * MAP_UNIT - MAP_UNIT;
							}
						}
					}
				}
			}
			bubbleArray.length = L;
			trace(_gameLayer.width, _gameLayer.height);
		}

		//设置stone初始化
		private function setBullet():void {			
			bullet = currentBullet;
			bullet.x = _shooter.x-bullet.width/2;
			bullet.y = _shooter.y - bullet.height / 2 - 2;
			//创建下一个stone
			nextBullet = new Bubble();
			nextBullet.createBubble();
			nextBullet.x = _shooter.x-nextBullet.width/2+80;
			nextBullet.y = _shooter.y - nextBullet.height / 2 - 2;
			addChild(nextBullet);
		}

		private function clickHandler(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			//发射的音效
			AudioRockman.play(Audio.SHOOT_NEW);
			//把上一个给待发射的
			currentBullet = nextBullet;
			currentBullet.x = _shooter.x-currentBullet.width/2;
			currentBullet.y = _shooter.y - currentBullet.height / 2 - 2;			
			//要发射的stone重新布局位置
			bullet.x = MAP_UNIT * (L - 1) / 2-10;
			bullet.y = MAP_UNIT * (L - 2);			
			_gameLayer.addChildAt(bullet,_gameLayer.numChildren);
			initX = _shooter.x ;
			initY = _shooter.y ;
			shot(GameSetting.stoneSpeed);
		}

		//发射
		private function shot(v:Number):void {
			//trace("angle="+_shooter.angle);
			_angle = _shooter.angle;
			if (_angle > 17 && _angle < 163) {
				_V = v;
				initMouseX = stage.mouseX;
				initMouseY = stage.mouseY;
				_vx =_V * Math.cos(Math.atan((initMouseY - initY) / (initMouseX - initX )));
				_vy =_V * Math.sin(Math.atan((initMouseY - initY) / (initMouseX - initX )));		
				//trace("_vx=" + _vx, "_vy=" + _vy);			
				addEventListener(Event.ENTER_FRAME, onFrameHandler);
			}
		}

		private function onFrameHandler(e:Event):void {	
			//子弹运动规则			
			if (initMouseX >= initX) {
				bullet.x += -_vx;
				bullet.y += -_vy;
			}else if (initMouseX < initX) {
				bullet.x += _vx;
				bullet.y += _vy;
			}
			
			if (bullet.x < MAP_UNIT/2+10){
				bullet.x = MAP_UNIT/2+10;
				_vx *= -1;
			} else if (bullet.x > W - MAP_UNIT * 3.7){
				bullet.x = W - MAP_UNIT * 3.7;
				_vx *= -1;
			}
			if (bullet.y < -MAP_UNIT) {				
				//碰到最底部的墙
				if (_gameLayer) {
					_gameLayer.removeChild(bullet);
					bullet = null;
					setBullet();
					//加两行stone
					addBubbles();
					checkNum = 0;
					removeEventListener(Event.ENTER_FRAME,onFrameHandler);
					stage.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
				}				
			}		
			
			//如果超出场地重新布置子弹
			if (bullet.y > MAP_UNIT * TOTALCOL) {
				setBullet();				
				removeEventListener(Event.ENTER_FRAME, onFrameHandler);
				stage.addEventListener(MouseEvent.CLICK, clickHandler);
			}			
			checkHit();
			
			//游戏容器逐渐向上移动
			//moveUpFunc();
		}
		
		private function moveUpFunc():void {
			
		}
				
		//检测碰撞，提取被撞者的row 和col
		private function checkHit():void {
			//trace (bubbleArray.length)
			for (var r:uint = 0; r < bubbleArray.length; r++){
				for (var c:uint = 0; c < TOTALCOL; c++){
					if (bubbleArray[r][c]){
						if (bullet.hitPiont.hitTestObject(bubbleArray[r][c].hitPiont)) {
						//if (bullet.hitTestObject(bubbleArray[r][c])){						
							//AudioRockman.play(Audio.HIT_NEW);
							_vx = 0;
							_vy = 0;
							row = r;
							col = c;
							setPosition();
							setBullet();
							break;
							return;
						}
					}
				}
			}
		}

		//第一个难点出现，即碰撞后的放置
		private function setPosition():void {			
			stage.addEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			//在Bubble里面写了个getSuroundPosition()方法，找到周围的六个点
			var suroundPositionArr:Array = bubbleArray[row][col].getSuroundPosition();
			var distanceArr:Array = new Array();
			for (var i:uint = 0; i < suroundPositionArr.length; i++){
				//碰撞后的点与上述六个点的距离放入数组
				distanceArr.push([bullet.getDistance(suroundPositionArr[i]) / 10, i]);

			}
			//大小排序
			distanceArr.sort();
			//trace(distanceArr);
			// 先以最近的点放置
			setSuitablePlace(distanceArr[0][1]);
			function setSuitablePlace(num:uint):void {
				//很多特殊情况得一一手动排除，包括奇偶行的差别，还有墙壁
				switch (num){
					case 0:
						if (col == 0){
							if (row % 2 == 0){
								core_r = row - 1;
								core_c = col;
							} else {
								core_r = row - 1;
								core_c = col + 1;
							}
							bullet.x = suroundPositionArr[1][0];
							bullet.y = suroundPositionArr[1][1];
							break;
						} else {
							if (row % 2 == 0){
								core_r = row - 1;
								core_c = col - 1;
							} else {
								core_r = row - 1;
								core_c = col;
							}
							bullet.x = suroundPositionArr[0][0];
							bullet.y = suroundPositionArr[0][1];
							break;
						}
					case 1:
						if (col == 12){
							if (row % 2 == 0){
								core_r = row - 1;
								core_c = col - 1;
							} else {
								core_r = row - 1;
								core_c = col;
							}
							bullet.x = suroundPositionArr[0][0];
							bullet.y = suroundPositionArr[0][1];
							break;
						} else {
							if (row % 2 == 0){
								core_r = row - 1;
								core_c = col;
							} else {
								core_r = row - 1;
								core_c = col + 1;
							}
							bullet.x = suroundPositionArr[1][0];
							bullet.y = suroundPositionArr[1][1];
							break;
						}
					case 2:
						core_r = row;
						core_c = col + 1;
						bullet.x = suroundPositionArr[2][0];
						bullet.y = suroundPositionArr[2][1];
						break;
					case 3:
						//trace("3");
						if (col == 12){
							if (row % 2 == 0){
								core_r = row + 1;
								core_c = col - 1;
							} else {
								core_r = row + 1;
								core_c = col;
							}
							bullet.x = suroundPositionArr[4][0];
							bullet.y = suroundPositionArr[4][1];
							break;
						} else {
							if (row % 2 == 0){
								core_r = row + 1;
								core_c = col;
							} else {
								core_r = row + 1;
								core_c = col + 1;
							}
							bullet.x = suroundPositionArr[3][0];
							bullet.y = suroundPositionArr[3][1];
							break;
						}
					case 4:
						//trace ("4")
						if (col == 0){
							if (row % 2 == 0){
								core_r = row + 1;
								core_c = col;
							} else {
								core_r = row + 1;
								core_c = col;
							}
							bullet.x = suroundPositionArr[4][0];
							bullet.y = suroundPositionArr[4][1];
							break;
						} else {
							if (row % 2 == 0){
								core_r = row + 1;
								core_c = col - 1;
							} else {
								core_r = row + 1;
								core_c = col;
							}
							bullet.x = suroundPositionArr[4][0];
							bullet.y = suroundPositionArr[4][1];
							break;
						}
					case 5:
						//trace("5");
						core_r = row;
						core_c = col - 1;
						bullet.x = suroundPositionArr[5][0];
						bullet.y = suroundPositionArr[5][1];
						break;
				}
			}
			//如果最近的被占，找次近的
			if (bubbleArray[core_r][core_c] is Bubble){
				//trace("IS");
				setSuitablePlace(distanceArr[1][1]);

			}
			//最后把子弹放入总数组
			bubbleArray[core_r][core_c] = bullet;			
			removeEventListener(Event.ENTER_FRAME, onFrameHandler);
			//开始以子弹为核心搜索
			startSearch();
			//结果大于2执行drop
			if (sameBubbleTotal.length > 2) {			
				checkNum = 0;
				addEventListener(Event.ENTER_FRAME, startEff);			
				//trace(this.numChildren);
			} else {
				checkNum += 1;
				if (checkNum == MINI){ //看是否应该增加stone
					addBubbles();
				}
				//看是否gameover
				for (var h:uint = 0; h < TOTALCOL - 1; h++){
					if (bubbleArray[11][h] is Bubble){
						gameOver();
						break;
					}
				}
			}			
		}
		
		private function startEff(e:Event):void {
			//下面是消除时的效果
			var ay:Number = 0.2;
			var vy:Number = 0;	
			for (var k:uint = 0; k < sameBubbleTotal.length; k++){
				vy += ay;
				sameBubbleTotal[k].y += vy;
				sameBubbleTotal[k].alpha *= 0.7;
				if (sameBubbleTotal[0].alpha < 0.1){
					//trace("IS");
					for (var kk:uint = 0; kk < sameBubbleTotal.length; kk++){
						//GameSound.disapearSound.play();
						
						var pointBurst:PointBurst = new PointBurst(sameBubbleTotal[kk].parent, "+1", sameBubbleTotal[kk].x, sameBubbleTotal[kk].y);
						_gameLayer.removeChild(sameBubbleTotal[kk]);
						bubbleArray[getRow(sameBubbleTotal[kk])][getCol(sameBubbleTotal[kk])] = null;
						sameBubbleTotal[kk] = null;							
						}
						
						//消除完检查是否该 gameover 
						if (sameBubbleTotal[sameBubbleTotal.length - 1] == undefined){
							//trace("ye");
							for (var h:uint = 0; h < TOTALCOL - 1; h++){
								if (bubbleArray[11][h] is Bubble){
									gameOver();
									break;
								}
							}
						}
					//以消除一个球得一分计算这次的得分，并加入总分中
					//var numPoints:uint = kk;
					//addScore(numPoints);
					removeEventListener(Event.ENTER_FRAME, startEff);
					//难点二的第一次搜索，
					search1();
					break;
				}
			}						
		}

		//开始搜索
		private function startSearch():void {
			//先手动搜索子弹的周围
			var firstArr:Array = firstSearch(bubbleArray[core_r][core_c]);
			//trace("firstArr=",firstArr);

			if (!firstArr) {
				sameBubbleTotal = null;
			} else {
				//如果有，继续搜索
				sameBubbleTotal = searchSameColor(firstArr);
				if (sameBubbleTotal.length > 2) {
					//奖励处理
					//trace("一般奖励")
					sendBonus(sameBubbleTotal);
					
				}
			}
		}

		//搜索相同颜色的stone，即第一次递归
		private function searchSameColor(arr:Array):Array {

			for (var i:uint = 0; i < arr.length; i++){
				//结果再加入自己的数组
				arr = arr.concat(searchAroundSameColor(bubbleArray, getRow(arr[i]), getCol(arr[i])));
				//trace("get=",getRow(arr[i]));
				//祛除重复
				for (var g:int = 0, temp:Array = []; g < arr.length; g++){
					if (temp.indexOf(arr[g]) == -1){
						temp.push(arr[g]);
					}
				}
				arr = temp;
			}
			//加入标尺
			lenArra.push(arr.length);
			//出口
			if (lenArra[lenArra.length - 1] == lenArra[lenArra.length - 2]){

				//trace(lenArra);
				return arr;
			} else {

				searchSameColor(arr);

				return arr;
			}
		}

		private function firstSearch(obj:Bubble):Array {
			var temArray:Array;
			var r:uint = getRow(obj);
			var c:uint = getCol(obj);
			//分几种情况
			if (r == 0){
				temArray = new Array(bubbleArray[r][c - 1], bubbleArray[r][c + 1], bubbleArray[r + 1][c - 1], bubbleArray[r + 1][c]);
					//trace("r==0");
			} else {

				if (r % 2 != 0){
					temArray = new Array(bubbleArray[r - 1][c], bubbleArray[r - 1][c + 1], bubbleArray[r][c - 1], bubbleArray[r][c + 1], bubbleArray[r + 1][c], bubbleArray[r + 1][c + 1]);
				} else {
					temArray = new Array(bubbleArray[r - 1][c - 1], bubbleArray[r - 1][c], bubbleArray[r][c - 1], bubbleArray[r][c + 1], bubbleArray[r + 1][c - 1], bubbleArray[r + 1][c]);
				}
			}
			//检查颜色类型是否一致，不一致要除掉
			for (var ii:int = temArray.length - 1; ii > -1; ii--){
				if (!(temArray[ii] is Bubble) || (temArray[ii] && temArray[ii].checkType() != bullet.checkType())){
					temArray.splice(ii, 1);
				}
			}
			return temArray;
		}

		//此递归函数的参数必须是个数组，此函数返回之
		private function searchAroundSameColor(arr:Array, r:uint, c:uint):Array {
			var temArr:Array;
			if (r % 2 != 0){

				temArr = new Array(arr[r - 1][c], arr[r - 1][c + 1], arr[r][c - 1], arr[r][c + 1], arr[r + 1][c], arr[r + 1][c + 1]);
					//}
			} else {
				if (r < 1){
					temArr = new Array(arr[r][c - 1], arr[r][c + 1], arr[r + 1][c - 1], arr[r + 1][c]);
				} else {
					temArr = new Array(arr[r - 1][c - 1], arr[r - 1][c], arr[r][c - 1], arr[r][c + 1], arr[r + 1][c - 1], arr[r + 1][c]);
				}
			}
			for (var ii:int = temArr.length - 1; ii > -1; ii--){
				if (!(temArr[ii] is Bubble) || (temArr[ii] && temArr[ii].checkType() != bullet.checkType())){
					temArr.splice(ii, 1);
				}
			}
			return temArr;
		}

		//第二个递归的基础，找连接的
		private function searchAroundNear(arr:Array, r:uint, c:uint):Array {
			var temArr:Array;
			if (r % 2 != 0){

				temArr = new Array(arr[r - 1][c], arr[r - 1][c + 1], arr[r][c - 1], arr[r][c + 1], arr[r + 1][c], arr[r + 1][c + 1]);

			} else {
				if (r < 1){
					temArr = new Array(arr[r][c - 1], arr[r][c + 1], arr[r + 1][c - 1], arr[r + 1][c]);
				} else {
					temArr = new Array(arr[r - 1][c - 1], arr[r - 1][c], arr[r][c - 1], arr[r][c + 1], arr[r + 1][c - 1], arr[r + 1][c]);
				}
			}
			for (var ii:int = temArr.length - 1; ii > -1; ii--){
				if (!(temArr[ii] is Bubble)){
					temArr.splice(ii, 1);
				}
			}
			return temArr;
		}

		//先从最顶层个一个开始
		private function search1():void {
			//trace("search1");
			for (var c:uint = 0; c < TOTALCOL; c++){

				if (bubbleArray[0][c] is Bubble){

					var arrayT:Array = searchAround(bubbleArray[0][c]);
					//还是去掉重复的
					for (var g:int = 0, temp:Array = []; g < arrayT.length; g++){
						;
						if (temp.indexOf(arrayT[g]) == -1){
							temp.push(arrayT[g]);
						}
					}
					arrayT = temp;
					//trace("leng=",arrayT,arrayT.length);
					temDropArr = [];
					//把剩下的放入数组
					for (var i:uint = 0; i < TOTALROW; i++){
						for (var j:uint = 0; j < TOTALCOL; j++){
							if ((bubbleArray[i][j] is Bubble) && arrayT.indexOf(bubbleArray[i][j]) == -1){
								//trace("bubbleArray[i][j]=",bubbleArray[i][j]);
								temDropArr.push(bubbleArray[i][j]);
							}
						}
					}
					//trace("temDropArr=",temDropArr.length);
					search2();
					//播放音效
					if (!_xkFlag) {
						soundEffect(sameBubbleTotal.length);
					}					
					break;
				} else {
					continue;
				}
			}
		}
		
		//计算奖励
		private function sendBonus(_arr:Array):void {
			var _bonusData:Object = new Object();
			var _petArr:Array = new Array();
			var _money:uint = 0;
			var _stoneNum:uint = 0;
			var _exp:uint = 0;
			_bonusData.money = 0;
			_bonusData.stoneNum = 0;
			_bonusData.exp = 0;
			
			for (var i:int = 0; i < _arr.length; i++) {
				if (_arr[i].getBonus() == "moneyBonus") {
					_money += Math.ceil(Math.random() * GameSetting.moneyGaps) + GameSetting.bonusMoney;
				}
			}
			_bonusData.money = _arr.length + _money;
			_bonusData.stoneNum = _arr.length;
			
			_bonusData.exp = _arr.length;
			//发送bonus数据
			sentBonusData(_bonusData);
			//判断是否过关
			_totalRockNum += _arr.length;
			_totalMoney += _money+_arr.length;
			if (_totalRockNum>=GameSetting.manExpArr[_saveData.user.level]) {				
				_bonus.save();
				rock_pause();
				_levelUp = new LevelUp();
				_levelUp.money_txt.text = String(_totalMoney);
				PopupWindow.init(stage);
				PopupWindow.show(_levelUp);
				_levelUp.btn_uplevel.addEventListener(MouseEvent.CLICK, levelUpHandler);
				_levelUp.btn_resume.addEventListener(MouseEvent.CLICK,resumeHandler);
			}			
		}
		
		private function levelUpHandler(e:MouseEvent):void {
			trace("levelup");
			closeLevelUp();
			dispatchEvent(new Event(CommonEvent.BACK_EVENT));
		}
		
		private function resumeHandler(e:MouseEvent):void {
			trace("contiune");
			closeLevelUp();
			rock_close();
			gamePort();			
		}
		
		private function closeLevelUp():void {
			_totalRockNum = 0;
			_totalMoney = 0;
			_levelUp.btn_uplevel.removeEventListener(MouseEvent.CLICK, levelUpHandler);
			_levelUp.btn_resume.removeEventListener(MouseEvent.CLICK,resumeHandler);
			PopupWindow.close();
			_levelUp = null;
		}

		//数据发送处理函数
		private function sentBonusData(_data:Object):void {						
			_bonus.show(_data);		
		}
		
		//第二次,执行递归。
		private function search2():void {
			_xkFlag = false;
			for (var i:uint = 0; i < temDropArr.length; i++){
				if (temDropArr[i] && getRow(temDropArr[i]) == 0) {
					var arrayT:Array = searchAround(bubbleArray[0][getCol(temDropArr[i])]);
					break;
				}
			}
			//如果该数组的对象都悬空，drop
			if (i == temDropArr.length && getRow(temDropArr[i - 1]) != 0) {
				doDrop(temDropArr);	
				_xkFlag = true;
				//播放音效
				soundEffect(sameBubbleTotal.length + temDropArr.length);
				//计算悬空奖励
				//trace("悬空奖励");
				sendBonus(temDropArr);
				//trace("第一次消除的岩石数", sameBubbleTotal.length, "第二次消除悬空岩石数", temDropArr.length);
			}
			
			if (arrayT) {
				dropArr = [];
				for (var j:int = 0; j < temDropArr.length; j++){

					if ((temDropArr[j] is Bubble) && arrayT.indexOf(temDropArr[j]) == -1){

						dropArr.push(temDropArr[j]);
					}
				}
				//trace("dropArr=",dropArr.length);
				if (dropArr[0]){

					temDropArr = dropArr;
				} else {
					return;
				}
				for (var k:int; k < temDropArr.length; k++){
					//判断递归出口
					if (temDropArr[k] is Bubble){
						//调用递归
						search2();
						break;
					} else {
						return;
					}
				}		
			}
		}

		//消除悬空的stone
		private function doDrop(array:Array):void {
			//trace("666666",array.length);
			addEventListener(Event.ENTER_FRAME, startEff);
			//添加消除时的效果
			var ay:Number = 0.3;
			var vy:Number = 0;
			function startEff(e:Event):void {
				for (var k:uint = 0; k < array.length; k++){
					//GameSound.dropSound.play();
					vy += ay;
					array[k].y += vy;
					array[k].alpha *= 0.8;

					if (array[0].alpha < 0.1){
						//记分
						//var numPoints:uint = array.length;
						//addScore(numPoints);
						
						for (var kk:int = array.length - 1; kk > -1; kk--){
							//添加得分效果
							var pointBurst:PointBurst = new PointBurst(array[kk].parent, "+1", array[kk].x, array[kk].y);
							//执行消除
							_gameLayer.removeChild(array[kk]);

							bubbleArray[getRow(array[kk])][getCol(array[kk])] = null;
							array[kk] = null;
							array.splice(kk, 1);
								//trace(pointBurst);
						}
						removeEventListener(Event.ENTER_FRAME, startEff);
						break;
					}
				}
			}
			
		}

		//用递归的方法找与目标相连的
		private function searchAround(obj:Bubble):Array {
			var c:uint = getCol(obj);
			var arrayD:Array;
			var array1:Array;
			array1 = new Array(bubbleArray[0][c - 1], bubbleArray[0][c + 1], bubbleArray[1][c - 1], bubbleArray[1][c]);
			//祛除空对象
			for (var i:int = array1.length - 1; i > -1; i--){
				if (!(array1[i] is Bubble)){
					array1.splice(i, 1);
				}
			}
			//如果没有，要返回它自己到数组
			if (!(array1[0] is Bubble)){
				return new Array(obj);
			} else {
				//跟找相同颜色的方法相似，少了个检查颜色
				arrayD = search(array1);
				//这里便是递归
				function search(arr:Array):Array {

					for (var ii:uint = 0; ii < arr.length; ii++){

						arr = arr.concat(searchAroundNear(bubbleArray, getRow(arr[ii]), getCol(arr[ii])));
						for (var iii:int = arr.length - 1; iii > -1; iii--){
							if (!(arr[iii] is Bubble)){
								arr.splice(iii, 1);
							}
						}

						for (var g:int = 0, temp:Array = []; g < arr.length; g++){
							;
							if (temp.indexOf(arr[g]) == -1){
								temp.push(arr[g]);
							}
						}
						arr = temp;
					}
					dropLenArr.push(arr.length);

					if (dropLenArr[dropLenArr.length - 1] == dropLenArr[dropLenArr.length - 2]){

						return arr;
					} else {

						search(arr);

						return arr;
					}
				}
				return arrayD;
			}

		}

		//加两行stone。
		private function addBubbles():void {
			//GameSound.addSound.play();
			for (var r:uint = 0; r < bubbleArray.length; r++){
				for (var c:uint = 0; c < TOTALCOL; c++){
					if (bubbleArray[r][c] is Bubble){
						bubbleArray[r][c].y += 60;
						//bubbleArray[r][c].y += MAP_UNIT;
					}
				}
			}
			var arr0:Array = new Array();
			var arr1:Array = new Array();
			for (var g:uint = 0; g < TOTALCOL; g++){
				var bubble0:Bubble = new Bubble();
				bubble0.createBubble(true);
				_gameLayer.addChildAt(bubble0, _gameLayer.numChildren);
				bubble0.x = MAP_UNIT * g + MAP_UNIT;
				bubble0.y = -MAP_UNIT;
				arr0.push(bubble0);
			}
			
			for (var h:uint = 0; h < TOTALCOL - 1; h++){
				var bubble1:Bubble = new Bubble();
				bubble1.createBubble(true);
				_gameLayer.addChildAt(bubble1, _gameLayer.numChildren);
				bubble1.x = MAP_UNIT * h + 3 * MAP_UNIT / 2;
				bubble1.y = 0;
				arr1.push(bubble1);
			}
			bubbleArray.unshift(arr1);			
			bubbleArray.unshift(arr0);
		}
		
		//晃动效果
		private function shakeLayer():void {
			//_tween = new Tween(_gameLayer, "y", None.easeInOut, H, H - 2, 1, true);
			//_tween.looping = true;
			
		}

		//获得任意stone在bubbleArray中的row和col
		private function getRow(obj:Object):uint {
			if (obj){
				var r:uint;
				var c:uint;
				for (r = 0; r < TOTALROW; r++){
					for (c = 0; c < TOTALCOL; c++){

						if (bubbleArray[r][c] == obj){
							return r;
						}
					}
				}
			}
			return r;
		}

		private function getCol(obj:Object):uint {
			if (obj){
				var r:uint;
				var c:uint;
				for (r = 0; r < TOTALROW; r++){
					for (c = 0; c < TOTALCOL; c++){
						if (bubbleArray[r][c] == obj){
							return c;
						}
					}
				}
			}
			return c;
		}
		
		//声音特效播放
		private function soundEffect(_length):void {
			switch (_length) {
				case 0:				
					break;
				case 1:				
					break;	
				case 2:				
					break;
				case 3:				
					break;	
				case 4:
					AudioRockman.play(Audio.GREAT_NEW);
					break;
				case 5:
					AudioRockman.play(Audio.WELL_DONE_NEW);
					break;
				case 6:
					AudioRockman.play(Audio.GOOD_JOB_NEW);
					break;
				case 7:
					AudioRockman.play(Audio.SUPERB_NEW);
					break;
				case 8:
					AudioRockman.play(Audio.WODERFULL_NEW);
					break;
				default:
					AudioRockman.play(Audio.PERFCT_NEW);
					break;
			}			
		}

		//gameover函数，可以以美工的方式实现，这里采取code
		private function gameOver():void {
			checkNum = 0;
			dispatchEvent(new Event(CommonEvent.GAME_OVER_EVENT));
		}

		//清除显示对象
		private function clearUp():void {
			for (var r:uint = 0; r < L; r++){
				for (var c:uint = 0; c < TOTALCOL; c++){
					if (bubbleArray[r][c]){
						_gameLayer.removeChild(bubbleArray[r][c]);
						bubbleArray[r][c] = null;
						delete bubbleArray[r][c];
					}
				}
			}
			
			if (nextBullet) {
				removeChild(nextBullet);
				nextBullet = null;
			}
						
			if (_shooter) {
				_shooter.clearAll();
				removeChild(_shooter);
				_shooter = null;				
			}
			_gameLayer.removeChild(wall);
			wall=null
			removeEventListener(Event.ENTER_FRAME, enFrameHandler);		
			stage.removeEventListener(MouseEvent.MOUSE_DOWN, clickHandler);
			removeEventListener(Event.ENTER_FRAME, startEff);
			
			if (_playTimer) {
				_playTimer.removeEventListener(TimerEvent.TIMER, playTimerHandler);
				_playTimer.stop();
				_playTimer = null;
			}
			
			removeChild(_bonus);
			_bonus = null;
		}
		
		private function playBgMusic():void {
			AudioRockman.play(Audio.FIGHT_MUSIC_TWO, true);
			_playTimer = new Timer(25000);
			_playTimer.addEventListener(TimerEvent.TIMER, playTimerHandler);
			_playTimer.start();
		}
		
		private function playTimerHandler(e:TimerEvent):void {
			stopBgMusic();
			var _rd:int = int(Math.ceil(Math.random() * 3));
			if (_rd == 1) {
				AudioRockman.play(Audio.FIGHT_MUSIC_TWO, true);
			}else if (_rd==2) {
				AudioRockman.play(Audio.FIGHT_MUSIC_THREE, true);
			}else {
				AudioRockman.play(Audio.FIGHT_MUSIC_FOUR, true);
			}
		}
		
		private function stopBgMusic():void {
			AudioRockman.stop(Audio.FIGHT_MUSIC_TWO);
			AudioRockman.stop(Audio.FIGHT_MUSIC_THREE);
			AudioRockman.stop(Audio.FIGHT_MUSIC_FOUR);
		}
		
/********************************************************************************/		
	}
}